/*
"source": {
	"item": {
		"mask": "MM-DD",
		"type": "timeCat",
		"tickCount": 5
	},
	"value": {
		"alias": "均质罐-出料-TS",
		"tickCount": 4,
		"tickInterval":2,//解决左侧出现小数点位数过多的情况
	}
}
*/
import React, { PureComponent } from "react"
import { Button } from "antd-mobile"
import { isNull, calcField } from "../../utils/helper"
import F2 from '@antv/f2/lib/index-all';
import getDataSource from "../MDatasource"
import MAction from '../MAction/MAction';
import moment from "moment";
window.moment = moment;
export default class MiLineBar extends PureComponent {
	constructor(props) {
		super(props)
		this.chart = null;
		this.timer = null;
		this.canvasId = Math.random() + new Date().getTime() + ""
		this.state = {
			no_data: false
		}
	}

	componentWillReceiveProps(next) {
		let { list: list1 = [] } = this.props;
		let { list: list2 = [], chart_config: { valueField } } = next;
		if (isNull(valueField)) {
			valueField = "value"
		}

		if (list1.length == 0 && list2.length > 0) {
			this.renderChart(list2)
		}
		else {
			if (!_.isEqual(list1, list2)) {
				// this.chart.changeData(list2);
				this.chart.clear();

				this.renderChart(list2)
			}
		}
	}
	setSource = (source) => {
		let newSource = {};
		for (let i in source) {
			let item = source[i];
			let newItem = {
				...item
			}
			let { formatter, range } = item;
			if (formatter) {
				newItem.formatter = (value) => {//格式化话x y轴的显示 比如 0-关 1-开 等
					return eval(formatter)
					// return formatter.replace(/\{\{item\}\}/g, val)
				}
			}
			if (isNull(range) || (!isNull(range) && range.length == 0)) {
				newItem.range = undefined
			}
			newSource[i] = newItem
		}
		return newSource
	}
	setLegend = (legend) => {
		let { position } = legend || {};
		if (isNull(position)) {
			position = "top"
		}
		return {
			...legend,
			position
		}
	}
	setTooltip = (tooltip) => {
		let { chart_config: { legend, render } } = this.props;
		let { showTitle, showCrosshairs, offsetY, custom } = tooltip || {};
		let { isGroup, isGradient, groupField } = render || {};
		let isCustom = false;
		if (custom == 1) {
			isCustom = true
		}
		if (isGroup != 1) {
			isCustom = false
		}
		if (isGradient == 1) {
			isCustom = false
		}
		if (isNull(offsetY)) {
			offsetY = 0;
			if (!isCustom) {
				offsetY = 10
			}
		}
		let legendPosition = "top";
		if (!isNull(legend) && !isNull(legend.position)) {
			legendPosition = legend.position;
		}
		return {
			...tooltip,
			showTitle: showTitle == 1,
			showCrosshairs: showCrosshairs == 1,
			offsetY,
			custom: isCustom,
			onShow: (obj) => {

			},
			onChange: (obj) => {
				if (isCustom) {
					let legend = this.chart.get('legendController').legends[legendPosition][0];
					let tooltipItems = obj.items;
					let legendItems = legend.items;
					let map = {};
					legendItems.map((item) => {
						map[item.name] = _.clone(item);
					});
					tooltipItems.map((item) => {
						let name = item.name;
						let value = item.value;
						if (map[name]) {
							map[name].value = value;
						}
					});
					legend.setItems(_.values(map));
				}
			},
			onHide: () => {
				if (isCustom) {
					let legend = this.chart.get('legendController').legends[legendPosition][0];
					legend.setItems(this.chart.getLegendItems().country);
				}
			}
		}
	}
	// https://f2.antv.vision/zh/docs/api/chart/guide/#line
	setGuide = (guide) => {
		for (let item in guide) {
			if (typeof this.chart.guide()[item] === "function") {
				if (guide[item] instanceof Array) {
					guide[item].map(i => {
						this.chart.guide()[item]({ ...i })
					})
				}
				else {
					this.chart.guide()[item]({ ...guide[item] })
				}
			}
		}
	}
	setTitle = () => {
		let { chart_config: { title } } = this.props;
		if (!isNull(title)) {
			return <div style={{ textAlign: "center", width: "100%", paddingTop: "5px" }} dangerouslySetInnerHTML={{ __html: title }}></div>;
		}
	}
	setCoord = (coord) => {
		let { transposed } = coord || {};
		if (!isNull(transposed) && transposed == 1) {
			transposed = true
		}
		else {
			transposed = false
		}
		return {
			...coord,
			transposed
		}
	}
	renderChart(data) {
		if (isNull(data) || data.length == 0) {
			this.setState({
				no_data: true
			})
			return;
		}
		this.setState({
			no_data: false
		})
		let { chart_config: { source, title, legend, tooltip, guide, render, coord, pinch, pinch_config, pan, pan_config, point }, height } = this.props;
		if (isNull(this.chart)) {
			let { width } = this.wrapper.getBoundingClientRect();
			this.chart = new F2.Chart({
				id: this.canvasId,
				// width: window.innerWidth,
				width: width,
				height: height ? height : window.innerWidth > window.innerHeight ? window.innerHeight - 54 : window.innerWidth * 0.618,
				pixelRatio: window.devicePixelRatio
			});
		}
		if (isNull(valueField)) {
			valueField = "value"
		}
		try {
			data = data.map(i => {
				let val;
				if (isNull(i[valueField])) {
					val = val
				}
				else {
					val = Number(i[valueField])
				}
				if (isNaN(val)) {
					return {
						...i
					}
				}
				else {
					return {
						...i,
						[valueField]: val
					}
				}
			})
		} catch (e) {
		}
		this.chart.source(data, {//渲染列定义
			...this.setSource(source)
		});
		this.chart.coord({
			...this.setCoord(coord)
		});

		//legend图例
		if (!isNull(legend)) {
			let { show, config } = legend;
			if (show === false) {// 不显示所有图例
				this.chart.legend(false);
			}
			else {
				if (!isNull(config)) {
					for (let i in config) {
						this.chart.legend(i, {
							...this.setLegend(config[i])
						});
					}
				}
			}
		}

		// tooltip 点击时的提示信息
		if (!isNull(tooltip)) {
			let { show, config } = tooltip;
			if (show === false) {
				this.chart.tooltip(false);
			}
			else {
				this.chart.tooltip({
					...this.setTooltip(config)
				})
			}
		}
		if (!isNull(guide)) {
			this.setGuide(guide);
		}
		// TODO:
		// this.chart.guide().line({ // 绘制辅助线
		// 	start: ['min', 6],
		// 	end: ['max', 6],
		// 	style: {
		// 		stroke: '#FF4D4F',
		// 		lineDash: [2]
		// 	}
		// });
	
		// this.chart.guide().text({ // 绘制辅助文本
		// 	position: ['max', 1],
		// 	content: '1',
		// 	offsetX: 10,
		// 	offsetY: 5,
		// 	style: {
		// 		fill: '#FF4D4F',
		// 		textAlign: 'end',
		// 		textBaseline: 'bottom'
		// 	}
		// });
		//posiiton x*y x和y轴分别对应的字段
		//isGroup 0||1是否分组 groupField 分组字段 groupShape 每个分组的曲线样式 	 line实线 dash虚线 smooth曲线 默认都是line
		let { isStack, position, groupField = "", isGroup, groupShape, type = "line", shape = "line", isGradient, gradientColor, colors, colorField, valueField, connectNulls, size } = render || {};
		if (isNull(connectNulls)) {
			connectNulls = true;
		}
		else {
			connectNulls = Boolean(connectNulls)
		}
		let chart;
		if (type === "bar") {
			if (isNull(size)) {
				chart = this.chart.interval().position(position).adjust({ type: "dodge", marginRatio: "0.05" })
			}
			else {
				chart = this.chart.interval().position(position).adjust({ type: "dodge", marginRatio: "0.05" }).size(size)
			}
		}
		else {
			chart = this.chart.line({ connectNulls }).position(position);
		}
		if (isGroup == 1 && isGradient != 1) {
			chart.color(groupField).shape(groupField, (name) => {
				let _shape = shape;
				for (let i in groupShape) {
					if (name === i && !isNull(groupShape[i])) {
						_shape = groupShape[i]
					}
				}
				return _shape;
			})
			if (isStack == 1) {
				chart.adjust("stack");
			}
		}
		else {
			if (!isNull(colorField) && !isNull(valueField)) {
				chart.color(valueField, (val) => {
					try {
						val = data.filter(item => item[valueField] == val)[0].zb;
					} catch (e) {

					}
					//根据值展示不同的颜色
					if (!isNull(colorField)) {
						if (!isNull(colors)) {
							for (let i in colors) {
								let color = colors[i];
								let value = calcField(i, { value: val * 1 });
								if (value) {
									return color;
								}
							}
						}
					}
					return ""
				})
			}
			else {
				chart.color("")
			}
			chart.shape(shape)
		}
		if (isGradient == 1) {
			// 使用 html5 canvas api 创建渐变色对象
			let canvas = document.getElementById(this.canvasId);
			let ctx = canvas.getContext('2d');
			let gradient = ctx.createLinearGradient(0, 0, window.innerWidth, 0);
			for (let i in gradientColor) {
				gradient.addColorStop(Number(i), gradientColor[i])
			}
			chart.color(gradient)
			this.chart.area().position(position).shape('line').color(gradient).animate({
				appear: {
					duration: 300,
					easing: "easeIn"
				}
			});
		}
		chart.animate({
			appear: {
				duration: 300,
				easing: 'easeIn'
			}
		})
		if (pinch) {
			if (isNull(pinch_config)) {
				pinch_config = {
					sensitivity: 0.1
				}
			}
			else {
				pinch_config = {
					sensitivity: 0.1,
					...pinch_config
				}
			}
			this.chart.interaction('pinch', {
				...pinch_config,
			});//缩放 
		}
		if (pan) {
			if (isNull(pan_config)) {
				pan_config = {
					sensitivity: 0.1
				}
			}
			else {
				pan_config = {
					sensitivity: 0.1,
					...pan_config
				}
			}
			this.chart.interaction('pan', {
				...pan_config
			});//平移 有缩放或者平移的时候 需要长按才会出现tooltip
		}
		if (pinch || pan) {
			this.chart.scrollBar({// 定义进度条
				mode: 'x',
				xStyle: {
					offsetY: -5
				}
			});
		}
		if (!isNull(point)) {
			let { lineWidth, fill } = point;
			this.chart.point().position(position).style('medalType', {
				...point
			});
		}

		this.chart.render();
		if (!isNull(this.props.event_key)) {// 如果event_key不为空 就给柱状图添加点击事件
			this.chart.interaction("interval-select", {
				"startEvent": "tap",
				unSelectStyle: null,
				onEnd: (e) => {
					let selected = e.selected;
					if (selected) {
						MAction({ ...this.props, formData: { ...this.props.formData, ...e.data } }, this.props.event_key);
					}
				}
			})
		}

	}
	componentDidMount() {
		let { width } = this.wrapper.getBoundingClientRect();
		let { list, dataset_key, height, chart_config: { valueField } } = this.props;

		if (isNull(valueField)) {
			valueField = "value"
		}
		try {
			list = list.map(i => {
				if (isNaN(Number(i[valueField]))) {
					return {
						...i
					}
				}
				else {
					return {
						...i,
						[valueField]: Number(i[valueField])
					}
				}
			})
		} catch (e) {

		}
		const data = list;
		this.chart = new F2.Chart({
			id: this.canvasId,
			// width: window.innerWidth,
			width: width,
			height: height ? height : window.innerWidth > window.innerHeight ? window.innerHeight - 54 : window.innerWidth * 0.618,
			pixelRatio: window.devicePixelRatio
		});
		// if (data.length > 0) {
		this.renderChart(data)
		// }
	}
	render() {
		let { list, height, no_data_msg = "未找到相关数据" } = this.props;
		height = height ? height : window.innerWidth > window.innerHeight ? window.innerHeight - 54 : window.innerWidth * 0.618;
		let { no_data } = this.state;
		return (
			<div ref={e => this.wrapper = e}>
				{this.setTitle()}
				<div className="chart-wrapper" style={{ display: no_data ? 'none' : '' }}>
					<canvas id={this.canvasId} />
				</div>
				{
					no_data && <div style={{ width: "100%", height: "50px", color: "#555" }} data-flex='cross:center main:center'>
						{no_data_msg}
					</div>
				}
			</div>
		)
	}

	componentWillUnmount() {
		clearInterval(this.timer)
	}
}